<?php
namespace backend\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii\db\Query;
use yii\db\Exception;



class Admin extends ActiveRecord
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    const STATUS = 1;
    public $role_id;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%admin}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    public static function findAllData()
    {
        $query = new \yii\db\Query();
        $query->select(['*'])->from('admin');
        $query->where(['deleted_at' => null]);
        $query->where(['status' => self::STATUS]);
        $command = $query->createCommand();
        $result = $command->queryAll();
        //var_dump($query->createCommand()->getRawSql());exit;
        return $result;
    }

    public static function selectData($field = '*',$data)
    {
        $query = new \yii\db\Query();
        $query->select([$field])->from('admin');
        $query->where(['deleted_at' => null]);
        $query->where(['status' => self::STATUS]);
        if(!empty($data['mobile'])){
            $query->andWhere(['like','mobile',$data['mobile']]);
        }
        if(!empty($data['true_name'])){
            $query->andWhere(['like','true_name',$data['true_name']]);
        }
        $command = $query->createCommand();
        $result = $command->queryAll();
        //var_dump($query->createCommand()->getRawSql());exit;
        return $result;
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password','true_name','mobile'], 'trim'],
            ['username', 'unique', 'message'=>'用户名已注册','on' => ['create','default']],
            [['username', 'password','true_name','id'], 'required','message' =>'{attribute}不能为空'],
            [['username'],'string','max'=>20, 'min'=>3, 'tooLong'=>'{attribute}请输入长度为3-20位字符', 'tooShort'=>'{attribute}请输入长度为3-20位字符'],
//            [['password'],'string','max'=>20, 'min'=>3, 'tooLong'=>'{attribute}请输入长度为3-20位字符', 'tooShort'=>'{attribute}请输入长度为3-20位字符'],
            [['true_name'],'string','max'=>20, 'min'=>2, 'tooLong'=>'{attribute}请输入长度为2-20位字符', 'tooShort'=>'{attribute}请输入长度为2-20位字符'],
            [['mobile'],'match','pattern'=>'/^[1][3456789][0-9]{9}$/','message' => '请输入正确的手机号'],
            [['username'],'match','pattern'=>'/^[0-9_a-zA-Z]{3,20}/','message' => '用户名只能由数字字母下划线组成'],
//            ['repassword', 'compare', 'compareAttribute'=>'password','message' => '两次输入密码不一致'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '用户id',
            'username' => '登录账号',
            'password' => '密码',
            //'repassword' => '确认密码',
            'true_name' => '真实姓名',
            'mobile' => '手机号',
            //'role_id' => '角色',
        ];
    }


    public function scenarios()
    {
        return [
            'default' => [
                'username',
                'password',
                'salt',
                'token',
                'mobile',
                'true_name',
                'repassword',
                'role_id'
            ],
            'create' => [
                'username',
                'password',
                'token',
                'salt',
                'status',
                'mobile',
                'true_name',
                'create_at',
                'update_at',
                'deleted_at',
            ],
            'update' => [
                'id',
                'username',
                'password',
                'salt',
                'token',
                'status',
                'mobile',
                'true_name',
                'create_at',
                'update_at',
                'deleted_at'
            ],
            'modify' => [
                'id',
                'password',
                'repassword',
            ],
            'modify_true' => [
                '!id',
                'password',
            ],
            'user_info' => [
                'true_name',
                'mobile',
                //'avatar',
            ],
        ];
    }

    /**
     * 插入更新数据
     * @author hey_heyang(635870453@qq.com)
     */
    public  function saveUserInfo($scenario, $data, $user_id = 0){
        if (!in_array($scenario, ['create', 'update'])) {
            return false;
        }
        $t = static::getDb()->beginTransaction();
        try {
            if ($scenario == 'update') {
                $user_id = intval($user_id);
                if (!$user_id) {
                    return false;
                }
                $model           = static::findOne(['id' =>$user_id]);
                if(empty($model)) throw new Exception('不存在此用户');
                $model->scenario = 'update';
                if(!empty($data['username'])){
                    $have_username = $this->find()->where(['username' =>$data['username']])->andWhere(['<>','id', intval($user_id)])->asArray()->one();
                    if(!empty($have_username)) throw new Exception('用户名已存在！');
                }

            } else {
                $model           = new self();
                $model->scenario = 'create';
                unset($data['id']);
                
            }
            $model->setAttributes($data, false);
            if (!$model->save()) {
                $t->rollBack();
                return $model;
            }else{
//                if($scenario == 'create'){
//                    $groupaccess_model = new AuthGroupAccess();
//                    $groupaccess_model::saveData(array('uid'=>intval($model->attributes['id']),'group_role_id'=>intval($data['role_id'])));
//                }
            }
            $model->refresh();
            $t->commit();

            return $model;
        } catch (Exception $e) {
            $t->rollback();
            return $e;
        }
    }

    /**
     * 更新密码
     * @param  array $params
     * @param  array $user_id
     * @author hey_heyang(635870453@qq.com)
     * @return array|bool|\yii\db\ActiveRecord[]
     */
    public static function modifyPassword($params,$user_id)
    {
        $t = static::getDb()->beginTransaction();
        try {
            $model           = static::findOne(['id' =>intval($user_id)]);
            $model->scenario = 'modify_true';
            $info = $model->toArray();
            $params['password'] = sha1(md5($params['password'].$info['salt']));
            $model->setAttributes($params, false);
            if (!$model->save()) {
                $t->rollBack();
                return $model;
            }
            $model->refresh();
            $t->commit();
            return $model;
        } catch (Exception $e) {
            $t->rollback();
            return $e;
        }
    }


    /**
     * 更新用户信息
     * @param  array $params
     * @param  array $user_id
     * @author hey_heyang(635870453@qq.com)
     * @return array|bool|\yii\db\ActiveRecord[]
     */
    public static function updateUserInfo($params,$user_id)
    {
        $t = static::getDb()->beginTransaction();
        try {
            $model           = static::findOne(['id' =>intval($user_id)]);
            $model->scenario = 'user_info';
            $model->setAttributes($params, false);
            if (!$model->save()) {
                $t->rollBack();
                return $model;
            }
            $model->refresh();
            $t->commit();
            return $model;
        } catch (Exception $e) {
            $t->rollback();
            return $e;
        }
    }

    /**
     * 删除会员
     * @param $user_id
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function deleteUser($user_id){
        $model = static::findOne(['id' =>$user_id]);
        if(empty($model)) return false;
        if($model->super==1) return false ;
        $params['status'] = 3;
        $params['deleted_at'] = time();
        $model->scenario = 'update';
        $model->setAttributes($params, false);
        if (!$model->save()) {
            return false;
        }else{
            return true;
        }
    }

    /**
     * 批量删除
     * @param $param
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function batchDel($param){
        $t = static::getDb()->beginTransaction();
        try {
            $ids=explode(',',$param['ids']);
            if(empty($ids)) return array('error'=>'参数错误');
            $res=$this::updateAll(['status' => 3,'deleted_at'=>time()], ['in','id' ,$ids]);
            if (!$res) {
                $t->rollBack();
                return array('error'=>'操作失败');
            }else{
                $this->refresh();
                $t->commit();
                return array('error'=>'');
            }
        }catch (Exception $e) {
            $t->rollback();
            return array('error'=>'操作失败');
        }

    }

    /**
     * 获取会员列表
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getUserList($params){
        if(!empty($params['true_name']) && !empty($params['mobile'])){
            $condition = ['and','admin.status=1',['like','admin.true_name',$params['true_name']],['like','admin.mobile',$params['mobile']],['admin.deleted_at'=>null]];
        }elseif(!empty($params['true_name'])){
            $condition = ['and','admin.status=1',['like','admin.true_name',$params['true_name']],['admin.deleted_at'=>null]];
        }elseif(!empty($params['mobile'])){
            $condition = ['and','admin.status=1',['like','admin.mobile',$params['mobile']],['admin.deleted_at'=>null]];
        }else{
            $condition['admin.status']=1;
        }
        $list = (new Query())
            ->select('admin.id,admin.username,GROUP_CONCAT(auth_group.title) as role,admin.true_name,admin.mobile')
            ->from('admin')
            ->leftJoin('auth_group_access','auth_group_access.uid=admin.id')
            ->leftJoin('auth_group','auth_group_access.group_role_id=auth_group.id')
            ->where($condition)
            ->groupBy('id')
            ->all();
        return empty($list)?array():$list;
    }

    /**
     * @inheritdoc
     */
    public static function findDataByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS]);
    }


}
